import styles from '../../assets/css/Doctor/DoctorScheduling.module.css'
import { useSelector } from 'react-redux'
import { getDoctorScheduling, getDoctorEdit } from '../../api/Doctor/DoctorScheduling'
import { useEffect, useState } from 'react';
import { Button, message } from 'antd'

export default function DocScheduling() {
    const user = useSelector(state => state.userSlice.user);
    const [data, setData] = useState([])

    useEffect(() => {
        // 获取当前日期的年月信息
        const currentYear = new Date().getFullYear();
        const currentMonth = new Date().getMonth() + 1;  // 月份是从0开始的，所以加1
        const currentDate = new Date(currentYear, currentMonth, 0); // 获取当前月的最后一天
        const daysInCurrentMonth = currentDate.getDate(); // 当前月的天数

        // 获取后端返回的排班数据
        getDoctorScheduling({ id: user.id })
            .then(res => {
                const originalData = JSON.parse(res.data[0].date);

                // 判断后端数据中的日期是否属于当前月份，如果不是，则生成当前月的数据
                const newRes = originalData.map(item => {
                    const itemDate = new Date(item.date);
                    const itemYear = itemDate.getFullYear();
                    const itemMonth = itemDate.getMonth() + 1;

                    // 如果后端日期不属于当前月份，则重新生成日期
                    if (itemYear !== currentYear || itemMonth !== currentMonth) {
                        const newDate = `${currentYear}-${currentMonth.toString().padStart(2, '0')}-${item.date.split('-')[2]}`;
                        return {
                            ...item,
                            date: newDate,
                        };
                    }

                    return item;
                });

                // 如果后端数据的天数不足当前月份的天数，补充新的日期数据
                const updatedData = [];
                for (let i = 1; i <= daysInCurrentMonth; i++) {
                    const currentDay = `${currentYear}-${currentMonth.toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`;
                    const dayData = newRes.find(item => item.date === currentDay) || { date: currentDay, morning: 0, afternoon: 0, night: 0 };
                    updatedData.push(dayData);
                }

                setData(updatedData);
            })
    }, [user.id]);

    // 切换选择状态的函数
    const handleSelect = (index, timePeriod) => {
        const newData = [...data];
        if (timePeriod === 'morning') {
            newData[index].morning = newData[index].morning === 0 ? 1 : 0;
        } else if (timePeriod === 'afternoon') {
            newData[index].afternoon = newData[index].afternoon === 0 ? 1 : 0;
        } else if (timePeriod === 'night') {
            newData[index].night = newData[index].night === 0 ? 1 : 0;
        }
        setData(newData);
    }

    const handleSubmit = async () => {
        // const newData = JSON.stringify(data).replace(/"/g, "\"");
        const newData = JSON.stringify(data);
        
        const res = await getDoctorEdit({ id: user.id, newdate: newData })
        if (res.code === 1) {
            message.success(res.msg)
        }

    }

    return (
        <div className={styles.body}>
            <header className={styles.header}>
                <img src={user.head} alt="" />
                <p>科室：{user.department}</p>
            </header>
            <main className={styles.main}>
                {
                    data.map((ele, index) => {
                        return (
                            <div className={styles.list} key={index}>
                                <div className={`${styles.list_item} ${styles.list_title}`}>{ele.date}</div>
                                <div
                                    className={`${styles.list_item} ${ele.morning === 1 ? styles.selected : ''}`}
                                    onClick={() => handleSelect(index, 'morning')}
                                >
                                    上午
                                </div>
                                <div
                                    className={`${styles.list_item} ${ele.afternoon === 1 ? styles.selected : ''}`}
                                    onClick={() => handleSelect(index, 'afternoon')}
                                >
                                    中午
                                </div>
                                <div
                                    className={`${styles.list_item} ${ele.night === 1 ? styles.selected : ''}`}
                                    onClick={() => handleSelect(index, 'night')}
                                >
                                    下午
                                </div>
                            </div>
                        );
                    })
                }
            </main >
            <footer className={styles.footer}>
                <Button onClick={handleSubmit} type='primary'>确认修改排班</Button>
            </footer>
        </div >
    );
}
